<template>
  <view class="content">
    <view class="top">
      <image class="bg" src="@/static/image/login/bg-for-top.png" />
      <image class="logo" src="@/static/image/login/logo.svg" />
    </view>
    <view class="form">
      <view class="method">
        <view class="specific-method" :class="{ 'active-method': loginMode === 0 }" @click="loginMode = 0">
          <span>免密登录</span>
        </view>
        <view class="specific-method" :class="{ 'active-method': loginMode === 1 }" @click="loginMode = 1">
          <span>密码登录</span>
        </view>
      </view>
      <view class="form-content">
        <form-input placeholder="手机号" v-model="phoneNumber" input-left-margin="15rpx">
          <template #input-left>
            <international-phone-prefix-selector v-model="phoneAreaCode">
              +{{ phoneAreaCode }}
              <uni-icons custom-prefix="iconfont" type="icon-down" size="15"></uni-icons>
            </international-phone-prefix-selector>
          </template>
        </form-input>
        <form-input placeholder="验证码" v-if="loginMode === 0" v-model="code">
          <template #input-right>
            <send-code-button :send-code="sendCode" class="send-code-button">
              <template v-slot="{ remainder, isWait }">
                <span :style="{ color: isWait ? '#999999' : '#ff644d' }">{{
                  isWait ? `${remainder}秒后可重发` : '获取验证码'
                }}</span>
              </template>
            </send-code-button>
          </template>
        </form-input>
        <form-input :password="!isPasswordVisible" placeholder="密码" v-if="loginMode === 1" v-model="password">
          <template #input-right>
            <view class="password-right">
              <eye-switch ref="eyeSwitchRef" size="18px" />
              <span class="forgot-password">忘记密码?</span>
            </view>
          </template>
        </form-input>

        <view class="submit" @click="toLogin">登录</view>
        <shake-text class="agreement" ref="shakeTextRef">
          <checked-switch v-model="isAgreeAgreement" />
          <span style="color: #999">我已阅读并同意</span><span style="color: #ff644d">《用户服务协议》</span
          ><span style="color: #999">和</span><span style="color: #ff644d">《隐私政策》</span>
        </shake-text>
      </view>
    </view>
    <view class="rider-recruit-button-box">
      <view class="rider-recruit-button" @click="toRegister">
        <uni-icons type="flag-filled" color="#FF644D" size="14" />
        骑手招募
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import InternationalPhonePrefixSelector from '@/components/international-phone-prefix-selector/index.vue'
import SendCodeButton from '@/components/send-code-button/index.vue'
import CheckedSwitch from '@/components/checked-switch/index.vue'
import ShakeText from '@/components/shake-text/index.vue'
import EyeSwitch from '@/components/eye-switch/index.vue'
import FormInput from '@/components/form-input/index.vue'
import { $modal } from '@/plugins'
import $API from '@/api'
import $store from '@/store'
// 检查是否存在token,当有时转到首页，只有没有用户信息时才能进入登录页面
if ($store.user.tokens.hasLoginInfo()) uni.redirectTo({ url: '/pages/index/index' })
// 当前登录方式
const loginMode = ref(0) // 0 手机验证码登录，1 账号密码登录
const phoneAreaCode = ref('86')
const phoneNumber = ref('')
const password = ref('')
const code = ref('')
// 是否同意协议
const isAgreeAgreement = ref(false)
const shakeTextRef = ref()
// 密码是否可见
const eyeSwitchRef = ref()
const isPasswordVisible = computed(() => (eyeSwitchRef.value?.isOpen === undefined ? false : eyeSwitchRef.value.isOpen))
// 发送验证码（返回Promise，如果异常，则不可重新发送验证码，成功发送后，会进行验证码重发倒计时）
async function sendCode() {
  // 手机号校验
  if (phoneNumber.value == '') {
    throw new Error($modal.toastErrorMsg('请输入手机号！'))
  }
  // 发送验证码
  const result = await $API.rider.sendCodeForRiderLogin(phoneAreaCode.value, phoneNumber.value)
  if (!result.success) {
    // 抛出异常后将取消倒计时
    throw new Error($modal.toastErrorMsg('异常！'))
  }
}
// 登录
async function toLogin() {
  // 需要同意协议
  if (!isAgreeAgreement.value) {
    shakeTextRef.value.triggerShake()
    return
  }
  // 表单必要性校验
  if (phoneNumber.value == '') {
    $modal.toastErrorMsg('请输入手机号！')
    return
  }
  if (loginMode.value === 0 && (code.value == null || code.value == '')) {
    $modal.toastErrorMsg(`请输入验证码！`)
    return
  }
  if (loginMode.value === 1 && (password.value == null || password.value == '')) {
    $modal.toastErrorMsg(`请输入密码！`)
    return
  }

  const result = await (loginMode.value === 0
    ? $API.rider.phoneCodeLogin({
        phoneAreaCode: phoneAreaCode.value,
        phoneNumber: phoneNumber.value,
        code: code.value
      })
    : $API.rider.passwordLogin({
        phoneAreaCode: phoneAreaCode.value,
        phoneNumber: phoneNumber.value,
        password: password.value
      }))
  if (!result.success) {
    // 登录失败
    $modal.toastErrorMsg(result.message)
    return
  }
  $store.user.tokens.setValue(result.data)
  // 登录成功后跳转到首页
  uni.redirectTo({ url: '/pages/index/index' })
}
// 跳到注册页面
function toRegister() {
  uni.navigateTo({ url: '/pages/register/index' })
}
</script>

<style scoped lang="scss">
.content {
  width: 100vw;
  height: 100vh;
  background: #f7f7f7;

  .top {
    $logo-size: 100px * 0.8;

    position: relative;
    padding-bottom: $logo-size * 0.3;
    width: 100vw;
    background-color: #fff;

    .bg {
      width: 100%;
    }

    .logo {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      margin: 0 auto;
      width: $logo-size;
      height: $logo-size;
      border-radius: 50%;
    }
  }

  .form {
    padding-bottom: 60px;
    background-color: #fff;
    border-bottom-left-radius: 30px;
    border-bottom-right-radius: 30px;

    .password-right {
      display: flex;
      flex-wrap: nowrap;

      .forgot-password {
        margin-left: 20rpx;
        color: #999;
      }
    }

    .form-content {
      padding: 0 10%;
      box-sizing: border-box;

      .basic-form-item:first-child {
        margin-top: 50rpx;
      }

      .phone {
        flex-grow: 1;
        margin-left: 20rpx;
      }

      .code {
        flex-grow: 1;
        margin-right: 20rpx;
      }

      .send-code-button {
        $send-code-button-height: 50rpx;

        display: inline-block;
        padding: 0 30rpx;
        height: $send-code-button-height;
        font-size: 26rpx;
        border-radius: $send-code-button-height * 0.5;
        color: #ff644d;
        background-color: #f7f7f7;
        line-height: $send-code-button-height;
        text-wrap: nowrap;
      }

      .submit {
        margin-top: 30px;
        height: 90rpx;
        border-radius: 8px;
        text-align: center;
        color: #fff;
        background: linear-gradient(
          90deg,
          rgb(255 153 0 / 100%) 0%,
          rgb(255 153 0 / 100%) 0%,
          rgb(254 70 1 / 100%) 100%,
          rgb(254 70 1 / 100%) 100%
        );
        line-height: 90rpx;
      }

      .agreement {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-top: 15px;
        font-size: 24rpx;
      }
    }

    .method {
      display: flex;
      justify-content: space-around;
      align-items: center;
      padding: 0 40rpx 40rpx;
      width: 100vw;
      font-size: 35rpx;
      color: #999;
      box-sizing: border-box;

      .active-method {
        font-weight: 700;
        color: #ff644d;
      }

      .specific-method::after {
        display: block;
        margin: 0 auto;
        margin-top: 5px;
        width: 80%;
        height: 5rpx;
        content: '';
      }

      .active-method::after {
        background-color: #ff644d;
      }
    }
  }

  .rider-recruit-button-box {
    display: flex;
    justify-content: center;
    padding-top: 40px;
    width: 100vw;

    .rider-recruit-button {
      display: inline-block;
      padding: 0 30rpx;
      height: 30px;
      font-size: 12px;
      border: 1px solid #ff644d;
      border-radius: 20px;
      color: #ff644d;
      line-height: 30px;
    }
  }
}
</style>
